package com.xyy.saas.payment.util;

import com.xyy.saas.payment.common.exception.PaymentException;
import com.xyy.saas.payment.payment.core.service.PaymentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class ConcatStringUtil {
    private static Logger LOGGER = LoggerFactory.getLogger(ConcatStringUtil.class);

    public static void main(String[] args) {
        System.out.println(JSONUtils.toJSON(addIntegerPrefix(1, 1, "YBM20211027185827148218", 10)));
        System.out.println(JSONUtils.toJSON(addIntegerPrefix(1, 11, "YBM20211027185827148218", 10)));
    }

    /**
     * @param prefix
     * @param start
     * @param originNo
     * @param size
     * @return
     * 11YBM20211027185827148218
     * 12YBM20211027185827148218
     * 13YBM20211027185827148218
     * ……
     * 110YBM20211027185827148218
     */
    public static List<String> addIntegerPrefix(Integer prefix, Integer start, String originNo, Integer size) {
        List<String> list = new ArrayList<>();

        for(int i = 0; i < size; i++) {
            StringBuilder no = new StringBuilder();
            no.append(prefix);
            no.append(start++);
            no.append(originNo);
            list.add(no.toString());
        }

        return list;
    }

    /**
     * 原始单号：20211027185827148218
     * 目标单号：
     * 20211027185827148218_01
     * 20211027185827148218_02
     * 20211027185827148218_03
     * …………
     * 20211027185827148218_99
     * @param sourceNO
     * @return
     * @throws PaymentException
     */
    public static String genNo(String sourceNO) throws PaymentException {
        String[] data = sourceNO.split("_");
        String no = data[0];
        String suffix = "01";

        if(data.length > 1) {
            try {
                int ps = Integer.parseInt(data[1]);
                ps += 1;

                if(ps > 99) {
                    throw new PaymentException("重试次数超过99次");
                }

                if(ps < 10) {
                    suffix = "0"+ps;
                }
                else {
                    suffix = String.valueOf(ps);
                }
            }
            catch(Exception e) {
                LOGGER.error(e.getMessage() ,e);
            }
        }

        return no + "_" + suffix;
    }
}
